//
//  successDemo.m
//  AoJi
//
//  Created by chen on 15/2/12.
//  Copyright (c) 2015年 xuanheng. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "successDemoView.h"
#import "PPiFlatSegmentedControl.h"
#import "MJRefresh.h"
#import "DataSingleTon.h"

NSString *const MJCollectionViewCellIdentifier = @"Cell";


@implementation successDemoView

#define MJRandomColor [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1]


- (AOJIBottomToolBar *)bottomToolBar {
    if (!_bottomToolBar) {
        _bottomToolBar = [[AOJIBottomToolBar alloc] initWithFrame:CGRectMake(0, 0, 320, 640)];
    }
    return _bottomToolBar;
}
- (NSMutableArray *)fakeColors
{
    if (!_fakeColors) {
        self.fakeColors = [NSMutableArray array];
        
        for (int i = 0; i<5; i++) {
            // 添加随机色
            [self.fakeColors addObject:MJRandomColor];
        }
    }
    return _fakeColors;
}
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        demoIndex = 1;
        offerIndex = 1;
        imgViews = [[NSMutableArray alloc] init];
        [self setBackgroundColor:[self getCorlor:@"ecedee"]];
        PPiFlatSegmentedControl *segmented2=[[PPiFlatSegmentedControl alloc] initWithFrame:CGRectMake(10, 5, 300, 30) items:@[               @{@"text":@"成功案例"},
                                                                                                                                                          @{@"text":@"Offer展示"},
        
                                                                                                                            ]
                                                                                          iconPosition:IconPositionRight andSelectionBlock:^(NSUInteger segmentIndex) {
                                                                                              if(segmentIndex ==0){
                                                                                                  NSLog(@"0");
                                                                                                  [self runsuccessdemo];
                                                                                              }
                                                                                              else {
                                                                                                  NSLog(@"1");
                                                                                                  [self runofferShow];
                                                                                              }
        
                                                                                          }];
                    segmented2.color=[UIColor whiteColor];
                    segmented2.borderWidth=2.0;
                    segmented2.borderColor=[UIColor colorWithRed:244.0f/255.0 green:67.0f/255.0 blue:60.0f/255.0 alpha:1];
                    segmented2.selectedColor=[UIColor colorWithRed:244.0f/255.0 green:67.0f/255.0 blue:60.0f/255.0 alpha:1];
                    segmented2.textAttributes=@{NSFontAttributeName:[UIFont systemFontOfSize:15],
                                                NSForegroundColorAttributeName:[UIColor redColor]};
                    segmented2.selectedTextAttributes=@{NSFontAttributeName:[UIFont systemFontOfSize:15],
                                                        NSForegroundColorAttributeName:[UIColor whiteColor]};
        
                    [self addSubview:segmented2];
    }
        successTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, 320,425) style:UITableViewStylePlain];
        successTableView.delegate = self;
        successTableView.dataSource = self;
        successTableView.tag = 998;
        [self addSubview:successTableView];
    
    successArray = [NSMutableArray array];
    offerListArray = [NSMutableArray array];
    [successTableView addFooterWithCallback:^{
        NSLog(@"加载更多。。。");
        [self refreshMoveData];
    }];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(80, 120);
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    layout.minimumInteritemSpacing = 20;
    layout.minimumLineSpacing = 20;

    offerCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, 320, 425) collectionViewLayout:layout];
    offerCollectionView.backgroundColor = kCorlor(231, 232, 234);
    offerCollectionView.alwaysBounceVertical = YES;
    offerCollectionView.dataSource = self;
    offerCollectionView.delegate = self;
    [offerCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:MJCollectionViewCellIdentifier];
    [offerCollectionView registerClass:[AOJIOfferCell class]forCellWithReuseIdentifier:@"offerCell"];

    [offerCollectionView addFooterWithCallback:^{
        NSLog(@"加载更多。。。");
        [self refreshCollectionData];
    }];
    [self addSubview:offerCollectionView];
    [self runsuccessdemo];
    
    return self;
}

- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [offerCollectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        for (int i = 0; i<5; i++) {
            [vc.fakeColors addObject:MJRandomColor];
        }
            [offerCollectionView reloadData];
            [offerCollectionView footerEndRefreshing];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [successArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        NSMutableDictionary* tempDic = [[NSMutableDictionary alloc] init];
         tempDic = [successArray objectAtIndex:indexPath.row];
        if(indexPath.row == 0){
            //标题
            UILabel* abstrLab = [[UILabel alloc] initWithFrame:CGRectMake(9, 7, 300, 15)];
            abstrLab.text = [tempDic objectForKey:@"abstracts"];
            abstrLab.font = [UIFont systemFontOfSize:17];
            abstrLab.textColor = [UIColor colorWithRed:52/255 green:52/255 blue:52/255 alpha:1.0];
            [cell addSubview:abstrLab];
            //图片
            UIImageView* imgShow = [[UIImageView alloc] initWithFrame:CGRectMake(9, 33, 302, 200)];
            NSString* finalUrl = [NSString stringWithFormat:@"%@%@",baseUrl,[tempDic objectForKey:@"img"]];
            
            [imgShow sd_setImageWithURL:[NSURL URLWithString:finalUrl] placeholderImage:nil];
            [cell addSubview: imgShow];
             //正文
            UILabel* contextLab = [[UILabel alloc] initWithFrame:CGRectMake(9, 220, 320, 50)];
            contextLab.text = [tempDic objectForKey:@"title"];
            contextLab.font = [UIFont systemFontOfSize:11];
            contextLab.textColor = [self getCorlor:@"989898"];
            [cell addSubview:contextLab];
            
            UILabel* timeStamp = [[UILabel alloc] initWithFrame:CGRectMake(250, 248, 100, 25)];
            NSString* timeStr = [tempDic objectForKey:@"dates"];
            timeStamp.text = [self getTime:timeStr];
            timeStamp.textColor = [self getCorlor:@"989898"];
            timeStamp.font = [UIFont systemFontOfSize:11];
            [cell addSubview:timeStamp];
            
        }
        else{
            UILabel* abstrLab = [[UILabel alloc] initWithFrame:CGRectMake(9, 7, 300, 20)];
            abstrLab.text = [tempDic objectForKey:@"abstracts"];
            abstrLab.font = [UIFont systemFontOfSize:17];
            [cell addSubview:abstrLab];
            
            UILabel* contextLab = [[UILabel alloc] initWithFrame:CGRectMake(9, 25, 320, 25)];
            contextLab.text = [tempDic objectForKey:@"title"];
            contextLab.font = [UIFont systemFontOfSize:11];
            contextLab.textColor = [self getCorlor:@"989898"];
            [cell addSubview:contextLab];
            
            UILabel* timeStamp = [[UILabel alloc] initWithFrame:CGRectMake(250, 45, 100, 25)];
            NSString* timeStr = [tempDic objectForKey:@"dates"];
            timeStamp.text = [self getTime:timeStr];
            timeStamp.textColor = [self getCorlor:@"989898"];
            timeStamp.font = [UIFont systemFontOfSize:11];
            [cell addSubview:timeStamp];
        }

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 270;
    }
    else{
        return 68;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString* webViewUrl = [NSString stringWithFormat:@"%@study/cases/detail?id=%@",baseUrl,[[successArray objectAtIndex:indexPath.row] objectForKey:@"id"]];
    
    DetailWebViewController *webVc=[[DetailWebViewController alloc]init];
    
    NSString *str=webViewUrl;
    webVc.urlString=str;
    [[self viewController].navigationController pushViewController:webVc animated:YES];

}

- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

-(void)runsuccessdemo{
    successTableView.hidden = false;
    offerCollectionView.hidden = true;
    NSMutableDictionary* dicSave = [[NSMutableDictionary alloc] init];
    [dicSave setObject:[NSString stringWithFormat:@"%ld",(long)demoIndex] forKey:@"startNum"];
    [dicSave setObject:[DataSingleTon shareDataSingleTon].catdir  forKey:@"country"];
    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:dicSave WithApi:@"study/cases" WhenSuccess:^(NSMutableDictionary *response) {
        for (id dic in response) {
            [successArray addObject:dic];
        }
        [successTableView reloadData];
        demoIndex++;
        [successTableView footerEndRefreshing];

    } WhenFailure:^(NSError *failure) {
        
    }];
}



-(void)runofferShow{
    successTableView.hidden = true;
    offerCollectionView.hidden = false;
    NSMutableDictionary* dicSave = [[NSMutableDictionary alloc] init];
    [dicSave setObject:[NSString stringWithFormat:@"%ld",(long)offerIndex] forKey:@"startNum"];
    [dicSave setObject:[DataSingleTon shareDataSingleTon].catdir  forKey:@"country"];
    [YHNetwork getInformationWithReguestType:RequestTypeGet WithParameters:dicSave WithApi:@"study/offer" WhenSuccess:^(NSMutableDictionary *response) {
        for (id dic in response) {
            [offerListArray addObject:dic];
        }
        [offerCollectionView reloadData];
        offerIndex++;
        [offerCollectionView footerEndRefreshing];
        
    } WhenFailure:^(NSError *failure) {
        
    }];
}

-(void)refreshMoveData{
    [self runsuccessdemo];
   
}

#pragma mark - collection数据源代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [offerListArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify3 = @"offerCell";
    AOJIOfferCell *offerCell = [collectionView dequeueReusableCellWithReuseIdentifier:identify3 forIndexPath:indexPath];
    
    
    offerCell.backgroundColor=[UIColor clearColor];
    
    if(!offerCell){
        offerCell = [[AOJIOfferCell alloc] init];
    }
    else{
        while ([offerCell.contentView.subviews lastObject] != nil)
        {
            [(UIView*)[offerCell.contentView.subviews lastObject] removeFromSuperview];
            
        }
//        [imgViews removeObject:offerCell.imgView];

    }
    
    NSInteger nDex = indexPath.row ;
    if (nDex < [offerListArray count]) {
        
        [offerCell configureCellWithFrame:collectionView.frame];
        NSDictionary *dic = [offerListArray objectAtIndex:nDex];
        
        [offerCell.imgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", baseUrl, [dic objectForKey:@"offerimg"]]] placeholderImage:nil];
        offerCell.schollName.text = [dic objectForKey:@"school"];
        
        //将图片放进图片数组
        [imgViews addObject:offerCell.imgView];
    }
    
    return offerCell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    AOJIOfferCell *Cell = (AOJIOfferCell *)[collectionView cellForItemAtIndexPath:indexPath];

    XHImageViewer *imageViewer = [[XHImageViewer alloc]
                                  initWithImageViewerWillDismissWithSelectedViewBlock:
                                  ^(XHImageViewer *imageViewer, UIImageView *selectedView) {
                                      NSInteger index = [imgViews indexOfObject:selectedView];
                                      NSLog(@"willDismissBlock index : %d", index);
                                  }
                                  didDismissWithSelectedViewBlock:^(XHImageViewer *imageViewer,
                                                                    UIImageView *selectedView) {
                                      NSInteger index = [imgViews indexOfObject:selectedView];
                                      NSLog(@"didDismissBlock index : %d", index);
                                  }
                                  didChangeToImageViewBlock:^(XHImageViewer *imageViewer,
                                                              UIImageView *selectedView) {
                                      NSInteger index = [imgViews indexOfObject:selectedView];
                                      NSLog(@"changeBlock to index : %d", index);
                                  }];
    imageViewer.delegate = self;
    imageViewer.disableTouchDismiss = NO;
    [imageViewer showWithImageViews:imgViews
                       selectedView:Cell.imgView];

}

-(void)refreshCollectionData{
    [self runofferShow];
    
}

#pragma mark - XHImageViewerDelegate

- (UIView *)customBottomToolBarOfImageViewer:(XHImageViewer *)imageViewer {
    return self.bottomToolBar;
}

- (void)imageViewer:(XHImageViewer *)imageViewer
willDismissWithSelectedView:(UIImageView *)selectedView {
    NSInteger index = [imgViews indexOfObject:selectedView];
    NSLog(@"willDismiss index : %d", index);
}

- (void)imageViewer:(XHImageViewer *)imageViewer
didDismissWithSelectedView:(UIImageView *)selectedView {
    NSInteger index = [imgViews indexOfObject:selectedView];
    NSLog(@"didDismiss index : %d", index);
}

- (void)imageViewer:(XHImageViewer *)imageViewer
didChangeToImageView:(UIImageView *)selectedView {
    NSInteger index = [imgViews indexOfObject:selectedView];
//    if (index <= [m_array_Data count])
//    {
//        NSDictionary *dic = [m_array_Data objectAtIndex:index];
//        _bottomToolBar.titleLabel.text = [dic objectForKey:@"school"];
//    }
    
}


@end
